// 控制吊顶+号创建代码组、库以及导入库的禁用，在库/组设置页修改后也会调用
import CreateProjectModalBoot from './dialog/createProject';
import ImportProjectModalBoot from './dialog/importProject';
import CreateGroupModalBoot from './dialog/createGroup';
import ProjectMenu from './dialog/createProject/projectMenu';
import GroupMenu from './dialog/createGroup/groupMenu';
import ImportProjectMenu from './dialog/importProject/projectMenu';
import CreateMRModalBoot from './dialog/createMR';
import { ConfigProvider } from '@teamix/ui';
import { access } from 'components/accessContainer/util';
import track from 'utils/track';
import { ENUM, ORGANIZATION_ADMIN_ROLES } from 'utils/constants.js';
import exceed from 'utils/apimap';
import utils from 'utils';
import intl from '../../locale';

const { id: org_id, user_role } = window.FORCE.organization;
const getCreateGroupAccess = (group_creator_role) => {
  return (
    access(ORGANIZATION_ADMIN_ROLES, user_role) ||
    group_creator_role.map((item) => ENUM.access_level[item]).includes(user_role)
  );
};
const getCreateProjectAccess = (repo_creator_identity) => {
  const cur_repo_creator_identity = utils.getCompatibleSettingData(repo_creator_identity);
  return (
    access(ORGANIZATION_ADMIN_ROLES, user_role) ||
    cur_repo_creator_identity.map((item) => ENUM.access_level[item]).includes(user_role)
  );
};

// 初始化新建入口需调用 repo_setting 和 group_setting 两个接口
// 为了延迟这两个接口调用，初始化新建入口时优先使用缓存
export default function initCreateEntrance(useCacheIfExist) {
  const repoSettingCacheKey = JSON.stringify({ type: 'new_repo_auth', orgId: org_id });
  const groupSettingCacheKey = JSON.stringify({ type: 'new_group_auth', orgId: org_id });
  const repoSettingCache = utils.getCachedData(repoSettingCacheKey);
  const groupSettingCache = utils.getCachedData(groupSettingCacheKey);

  // 若声明优先使用缓存，且缓存存在，则等两秒后重新执行init，并更新缓存
  if (useCacheIfExist && repoSettingCache && groupSettingCache) {
    setTimeout(() => {
      initCreateEntrance();
    }, 2000);
  }

  const getRespoSettingPromise = new Promise((resolve, reject) => {
    if (useCacheIfExist && repoSettingCache) {
      try {
        resolve({ repo_creator_identity: JSON.parse(repoSettingCache) });
        return;
      } catch (error) {
        console.error(error);
      }
    }
    exceed
      .fetch({
        api: 'organization.repo.setting.get',
        params: {
          org_id,
        },
      })
      .then((result) => {
        resolve(result);

        utils.setCachedData(repoSettingCacheKey, JSON.stringify(result.repo_creator_identity));
      })
      .fail((err) => {
        reject(err);
      });
  });
  const getGroupSettingPromise = new Promise((resolve, reject) => {
    if (useCacheIfExist && groupSettingCache) {
      try {
        resolve({ group_creator_role: JSON.parse(groupSettingCache) });
        return;
      } catch (error) {
        console.error(error);
      }
    }
    exceed
      .fetch({
        api: 'organization.group.setting.get',
        params: {
          org_id,
        },
      })
      .then((result) => {
        resolve(result);

        utils.setCachedData(groupSettingCacheKey, JSON.stringify(result.group_creator_role));
      })
      .fail((err) => {
        reject(err);
      });
  });

  Promise.all([getRespoSettingPromise, getGroupSettingPromise])
    .then((res) => {
      const [repoSetting, groupSetting] = res;
      const hasCreateProjectAccess = getCreateProjectAccess(repoSetting.repo_creator_identity);
      const hasCreateGroupAccess = getCreateGroupAccess(groupSetting.group_creator_role);
      const createEntranceArr = [
        {
          trigger: 'onClick',
          title: (
            <ConfigProvider prefix="yx-">
              <ProjectMenu hasAccess={hasCreateProjectAccess} />
            </ConfigProvider>
          ),
          action: 'custom',
          plugin: CreateProjectModalBoot,
          disabled: !hasCreateProjectAccess,
        },

        {
          trigger: 'onClick',
          title: (
            <ConfigProvider prefix="yx-">
              <ImportProjectMenu hasAccess={hasCreateProjectAccess} />
            </ConfigProvider>
          ),
          action: 'custom',
          plugin: ImportProjectModalBoot,
          disabled: !hasCreateProjectAccess,
        },

        {
          trigger: 'onClick',
          title: (
            <ConfigProvider prefix="yx-">
              <GroupMenu hasAccess={hasCreateGroupAccess} />
            </ConfigProvider>
          ),
          action: 'custom',
          plugin: CreateGroupModalBoot,
          disabled: !hasCreateGroupAccess,
        },

        {
          trigger: 'onClick',
          title: (
            <ConfigProvider prefix="yx-">
              <span
                onClick={() => {
                  track({
                    action: 'new_mr',
                    page: 'Ceiling',
                  });
                }}
                className="nav-create-cr"
              >
                {intl.get({
                  id: 'code-assets.utils.initNavigation.initCreateEntrance.CreateMergeRequest',
                  defaultMessage: '新建合并请求',
                })}
              </span>
            </ConfigProvider>
          ),
          action: 'custom',
          plugin: CreateMRModalBoot,
        },
      ];

      window.TB_NAVIGATION.CreateEntrance.register(createEntranceArr);
    })
    .catch((err) => {
      console.error(err);
    });
}
